using SPI.AgentServer.Services.Execution;
using System.Text;

namespace SPI.AgentServer.Services.Tools;

/// <summary>
/// 设备状态查询工具 - 查询设备在线状态、故障信息
/// 覆盖场景：D-001 离线摄像头, D-002 所有故障设备, D-003 指定区域故障设备, D-007 特定类型设备状态
/// </summary>
public class GetDeviceStatusTool : IQueryTool
{
    private readonly IDatabaseExecutor _executor;
    private readonly ILogger<GetDeviceStatusTool> _logger;

    public string Name => "get_device_status";
    public string Description => "查询设备在线状态和故障信息，支持按设备类型、区域、在线状态筛选。用于回答'哪些设备离线'、'设备故障列表'、'某区域设备状态'等问题。";

    public GetDeviceStatusTool(
        IDatabaseExecutor executor,
        ILogger<GetDeviceStatusTool> logger)
    {
        _executor = executor;
        _logger = logger;
    }

    public bool ValidateParameters(Dictionary<string, object> parameters, out List<string> errors)
    {
        errors = new List<string>();
        return true;
    }

    public async Task<ToolResult> ExecuteAsync(Dictionary<string, object> parameters, CancellationToken cancellationToken = default)
    {
        if (parameters == null)
        {
            return new ToolResult
            {
                Success = false,
                Errors = new List<string> { "参数不能为空" }
            };
        }

        try
        {
            // 获取参数
            string? deviceType = parameters.ContainsKey("deviceType") ? parameters["deviceType"]?.ToString() : null;
            string? areaName = parameters.ContainsKey("areaName") ? parameters["areaName"]?.ToString() : null;
            int? onlineStatus = parameters.ContainsKey("onlineStatus") ? Convert.ToInt32(parameters["onlineStatus"]) : null;
            bool onlyFaulty = parameters.ContainsKey("onlyFaulty") && Convert.ToBoolean(parameters["onlyFaulty"]);

            // 构建SQL
            var sql = BuildQuery(deviceType, areaName, onlineStatus, onlyFaulty);

            _logger.LogInformation("Executing device status query with SQL: {Sql}", sql);

            var result = await _executor.ExecuteQueryAsync(sql, null, cancellationToken);

            return new ToolResult
            {
                Success = true,
                Data = result.Data,
                Message = "设备状态查询成功",
                Metadata = new Dictionary<string, object>
                {
                    ["executionTimeMs"] = result.ExecutionTimeMs,
                    ["executedSql"] = sql
                }
            };
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error executing device status query");
            return new ToolResult
            {
                Success = false,
                Errors = new List<string> { $"查询失败: {ex.Message}" }
            };
        }
    }

    private string BuildQuery(string? deviceType, string? areaName, int? onlineStatus, bool onlyFaulty)
    {
        var sb = new StringBuilder();

        sb.AppendLine("SELECT");
        sb.AppendLine("    d.Name AS '设备名称',");
        sb.AppendLine("    d.CustomCode AS '设备编号',");
        sb.AppendLine("    dt.Name AS '设备类型',");
        sb.AppendLine("    a.Name AS '区域',");
        sb.AppendLine("    d.IpAddress AS 'IP地址',");
        sb.AppendLine("    d.UpdateTime AS '最后更新时间',");
        sb.AppendLine("    CASE d.OnLineStatus");
        sb.AppendLine("        WHEN 1 THEN '离线'");
        sb.AppendLine("        WHEN 2 THEN '在线'");
        sb.AppendLine("        ELSE '未知'");
        sb.AppendLine("    END AS '在线状态',");
        sb.AppendLine("    CASE d.ExceptionStatus");
        sb.AppendLine("        WHEN 1 THEN '正常'");
        sb.AppendLine("        WHEN 2 THEN '故障'");
        sb.AppendLine("        ELSE '未知'");
        sb.AppendLine("    END AS '异常状态'");
        sb.AppendLine("FROM TblDevice d");
        sb.AppendLine("LEFT JOIN TblDeviceType dt ON d.DeviceTypeId = dt.ID");
        sb.AppendLine("LEFT JOIN TblArea a ON d.StationAreaId = a.ID");
        sb.AppendLine("WHERE d.IsValid = 1");

        // 只查询故障设备（离线或有异常状态）
        if (onlyFaulty)
        {
            sb.AppendLine("    AND (d.OnLineStatus = 1 OR d.ExceptionStatus = 2)");
        }

        // 在线状态筛选
        if (onlineStatus.HasValue)
        {
            sb.AppendLine($"    AND d.OnLineStatus = {onlineStatus.Value}");
        }

        // 设备类型筛选
        if (!string.IsNullOrEmpty(deviceType))
        {
            // 特殊处理：摄像头的多种匹配关键词
            if (deviceType.Contains("摄像") || deviceType.Contains("camera") || deviceType.ToLower().Contains("ipc"))
            {
                sb.AppendLine("    AND (");
                sb.AppendLine("        dt.Name LIKE '%宇视网络摄像机%'");
                sb.AppendLine("        OR dt.Name LIKE '%摄像%'");
                sb.AppendLine("        OR dt.Name LIKE '%球机%'");
                sb.AppendLine("        OR dt.Name LIKE '%半球%'");
                sb.AppendLine("        OR dt.Name LIKE '%IPC%'");
                sb.AppendLine("        OR dt.Name LIKE '%Camera%'");
                sb.AppendLine("    )");
            }
            else
            {
                sb.AppendLine($"    AND dt.Name LIKE '%{deviceType}%'");
            }
        }

        // 区域筛选
        if (!string.IsNullOrEmpty(areaName))
        {
            sb.AppendLine($"    AND (a.Name LIKE '%{areaName}%' OR a.FullName LIKE '%{areaName}%')");
        }

        sb.AppendLine("ORDER BY d.OnLineStatus DESC, d.UpdateTime DESC");
        sb.AppendLine("LIMIT 100");

        return sb.ToString();
    }
}
